package com.jdy.haoduoaiteacher.socket;

import android.content.Context;
import android.content.Intent;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.util.LeConfig;

class SocketHeartThread extends Thread {
  boolean isStop = false;
  boolean mIsConnectSocketSuccess = false;
  static SocketHeartThread s_instance;

  private TCPClient mTcpClient = null;

  static final String tag = "SocketHeartThread";
  Intent status;
  private Context context;
  int a = 1;
  int b = 2;
  String heart = (char) a + "{\"data\": \"" + LeConfig.MAC_ID
      + "\", \"code\": 110}" + (char) b;

  public static synchronized SocketHeartThread instance() {
    if (s_instance == null) {
      s_instance = new SocketHeartThread();
    }
    return s_instance;
  }

  public SocketHeartThread() {
    status = new Intent("hk.com.dycx.intent.action.DEVICE_CONNECT_STATUS");
    context = MyTeacherApp.getAppContext();
    TCPClient.instance();
    // mIsConnectSocketSuccess = connect();

  }

  public void stopThread() {
    isStop = true;
  }

  private boolean reConnect() {
    return TCPClient.instance().reConnect();
  }

  @Override
  public void run() {
    isStop = false;
    while (!isStop) {

      boolean canConnectToServer = TCPClient.instance().canConnectToServer();
      System.out.println("====xxb===canConnectToServer===="
          + canConnectToServer + ";;;Const.connectF===" + Const.connectF);
      if (System.currentTimeMillis() - LeConfig.lasttime >= 14 * 1000) {
        if (Const.connectF != 0 && Const.connectF != 1) {
          status.putExtra("flag_online", 1);
          context.sendBroadcast(status);
          Const.connectF = 1;
        }
        reConnect();
      } else {
        if (!canConnectToServer) {
          if (Const.connectF != 0 && Const.connectF != 1) {
            status.putExtra("flag_online", 1);
            context.sendBroadcast(status);
            Const.connectF = 1;
          }
          reConnect();
        } else {
          if (!TCPClient.instance().isConnect()) {
            status.putExtra("flag_online", 1);
            context.sendBroadcast(status);
            Const.connectF = 1;
            reConnect();
          } else {
            if (Const.connectF != 2) {
              System.out.println("====xxb===Const.connectF===="
                  + Const.connectF);
              status.putExtra("flag_online", 2);
              context.sendBroadcast(status);
              Const.connectF = 2;
            }
          }
        }

      }
      try {
        Thread.sleep(Const.SOCKET_HEART_SECOND * 1000);

      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
